// pages/select-vehicle/select-vehicle.js
import { queryVehicle } from '../../services/vehicle'
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentIndex:0,
    currentItem:{},
    vehicleList:[],
    showDialogAlert: false,
    dialogMsg: ""
  },

  onLoad(options){
    const {id, name, vehicleType } = options
    let nowIndex = 0
    if(name){
      const allVehicleList = this.data.vehicleList
      for(let i= 0;i< allVehicleList.length;i++){
        if(name == allVehicleList[i]['name']){
          nowIndex = i
        }
      }
    }

    this.setData({
      currentIndex: nowIndex,
      currentItem:{
        id,
        name,
        vehicleType
      }
    })
  },

  onShow(){
    this.queryVehicleList()
  },

  async queryVehicleList(){
    let res = await queryVehicle()
    console.log("vehicle>>>",res)
    if(res.code === 200){
      let vehicleList = res.rows
      if(this.data.currentItem.id){
        let fIndex = vehicleList.findIndex(item => item.id === this.data.currentItem.id)
        console.log("fIndex>>>", fIndex)
        this.setData({
          currentIndex: fIndex
        })
      }
      this.setData({
        vehicleList: res.rows
      })
    }
  },

  confirmInfo(){
    console.log("this.data.currentItem>>>", this.data.currentItem)

    const { id, plateNo, vehicleType} = this.data.currentItem
    if(!id){
      this.setData({
        showDialogAlert:true,
        dialogMsg:"请先选择送检车辆!"
      })
      return
    }
    app.globalData.globalInfo.vehicleId = id
    app.globalData.globalInfo.plateNo = plateNo
    app.globalData.globalInfo.vehicleType = vehicleType 

    wx.navigateBack()
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit("infoChange", this.data.currentItem)
  },

  handleClick(e){
    const { currentindex, currentitem } = e.currentTarget.dataset
    this.setData({
      currentIndex: currentindex,
      currentItem: currentitem
    })
  },

  handleAddVehicle(){
    wx.navigateTo({
      url: '/pages/maintain-vehicle/maintain-vehicle',
    })
  },
})